<template>
  <div>
    <mt-popup v-model="visible" position="top" class="fdx-popup" ref="popup">
      <slot></slot>
    </mt-popup>
  </div>
</template>

<script>
const zIndex = 3000
export default {
  name: 'PosPopup',
  data() {
    return {
      visible: false
    }
  },
  methods: {
    position(el, container) {
      const self = this
      const popupEl = this.$refs.popup.$el
      const top = el.getBoundingClientRect().top + el.clientHeight
      popupEl.style.top = `${top}px`
      function findModal() {
        setTimeout(() => {
          const modalEl = document.querySelector('.v-modal')
          if (modalEl) {
            modalEl.style.marginTop = `${top}px`
            modalEl.onclick = function() {
              self.closeOnClickModal()
            }
          } else {
            findModal()
          }
        }, 50)
      }

      findModal()
    },
    closeOnClickModal() {
      this.$emit('close-modal')
    },
    toggle(el, container) {
      this.container = container
      this.position(el, container)
      if (!this.visible) {
        this.containerZIndex = window.getComputedStyle(container).zIndex
        container.style.zIndex = zIndex
      } else {
        this.setOriginalZIndex()
      }
      this.visible = !this.visible
    },
    setOriginalZIndex() {
      setTimeout(() => {
        this.container.style.zIndex = this.containerZIndex
      }, 300)
    },
    hide() {
      this.visible = false
    },
    close() {
      this.visible = false
      this.setOriginalZIndex()
    },
    isOpen() {
      return this.visible
    },
    show(el, container) {
      this.position(el, container)
      this.visible = true
    }
  }
}
</script>

<style scoped>
.fdx-popup {
  width: 100%;
  background-color: #fff;
  backface-visibility: hidden;
}
</style>
